<template>
  <el-dialog
    class="troila-dialog"
    :title="`${title}菜单`"
    :visible.sync="dialogFormVisible"
    :modal-append-to-body="true"
    :append-to-body="true"
    width="600px"
  >
    <el-form
      class="troila-form"
      :label-width="formLabelWidth"
      :model="form"
      :rules="rules"
      ref="form"
    >
      <el-form-item label="菜单名称" prop="menuName">
        <el-input
          v-model="form.menuName"
          auto-complete="off"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="菜单类型" prop="menuKind">
        <el-select
          v-setwidth
          placeholder="请选择"
          v-model="form.menuKind"
          clearable
          popper-class="troila-popper"
          @click.native="$store.commit('treeboxFn', null)"
          :disabled="(value && value.method === 'edit') || value === null"
        >
          <el-option
            v-for="(item, index) in menuKind"
            :key="index"
            :label="item.dictName"
            :value="item.dictCode"
            :disabled="judgeDisabled(item)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="上级菜单"
        :prop="form.menuKind == 2 ? 'parentId' : 'null'"
      >
        <treebox
          id="treebox"
          :list="menus_"
          v-model="form.parentId"
          placeholder="请选择"
          input
          :disabled="disabled"
          :clear="!disabled"
          onlyone
          :option="{ key: 'id', label: 'menuName' }"
          @return="returnTree"
        ></treebox>
        <!-- <el-tooltip class="helpTooltip" effect="dark" placement="right-top">
          <div slot="content">
            目录类型，若有父级菜单，父级菜单只能是目录<br />
            菜单类型，若有父级菜单，父级菜单只能是目录<br />
            按钮类型，若有父级菜单，父级菜单只能是菜单
          </div>
          <i class="el-icon-info"></i>
        </el-tooltip> -->
      </el-form-item>
      <el-form-item
        label="权限标识"
        :prop="form.menuKind == 2 ? 'menuCode' : 'null'"
      >
        <!--  v-if="form.menuKind != 0" -->
        <el-input
          v-model="form.menuCode"
          auto-complete="off"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="图标"
        prop="menuIcon"
        v-if="
          (form.menuKind == 0 || form.menuKind == 1) && form.menuKind !== ''
        "
      >
        <el-input
          v-model="form.menuIcon"
          auto-complete="off"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="menuAddr" v-if="form.menuKind == 1">
        <el-input
          v-model="form.menuAddr"
          auto-complete="off"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="显示顺序" prop="menuSort">
        <input-num v-model="form.menuSort" placeholder="请输入" />
      </el-form-item>
      <!-- <el-form-item
        label="菜单状态"
        prop="menuStatus"
        v-if="value && value.method == 'edit'"
      >
        <el-radio-group v-model="form.menuStatus">
          <el-radio
            :label="item.dictCode"
            v-for="item in menuList"
            :key="item.dictCode"
            >{{ item.dictName }}</el-radio
          >
        </el-radio-group>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="ajaxIng" @click="submitForm"
        >确 定</el-button
      >
      <el-button @click="dialogFormVisible = false">{{
        ajaxIng ? '关 闭' : '取 消'
      }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  name: 'menuForm',
  props: {
    value: {
      // true为添加，其他为编辑
      type: [Boolean, String, Number, Object],
      default: false,
    },
    menus: {
      // tree列表
      type: Array,
      default() {
        return []
      },
    },
  },
  data() {
    return {
      ajaxIng: false,
      dialogFormVisible: this.value ? true : false, //弹窗显示
      title: '',
      form: {
        menuName: '',
        menuKind: '',
        parentId: '',
        menuCode: '',
        menuAddr: '',
        menuIcon: '',
        menuSort: '',
      },
      formLabelWidth: '120px', //标题文字宽度
      rules: {
        // 规则
        menuName: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
        ],
        menuKind: [
          { required: true, message: '请选择菜单类型', trigger: 'change' },
        ],
        menuAddr: [
          { required: true, message: '请输入菜单地址', trigger: 'blur' },
        ],
        parentId: [
          { required: true, message: '请选择上级菜单', trigger: 'change' },
        ],
        menuCode: [
          { required: true, message: '请输入权限标识', trigger: 'blur' },
        ],
        // menuStatus: [
        //   { required: true, message: '请选择菜单状态', trigger: 'blur' },
        // ],
      },
      dictionary: {
        // 字典信息
        // menuKind: [
        //   { dictName: '目录', dictCode: 0 },
        //   { dictName: '菜单', dictCode: 1 },
        //   { dictName: '按钮', dictCode: 2 },
        // ],
        // menuStatus: [
        //   { dictName: '禁用', dictCode: '0' },
        //   { dictName: '启用', dictCode: '1' },
        // ],
      },
      disabled: false,
    }
  },
  computed: {
    menus_() {
      let list = [...JSON.parse(JSON.stringify(this.menus))]
      return this.toFilters(list)
    },
    menuList() {
      let list = this.$store.state.dictionary.menu_status
      if (!list) {
        this.$store.dispatch('dictionary/getDict', 'menu_status')
      }
      this.dictionary.menuStatus = list
      return list ? list : []
    },
    menuKind() {
      let list = this.$store.state.dictionary.menu_kind
      if (!list) {
        this.$store.dispatch('dictionary/getDict', 'menu_kind')
      }
      this.dictionary.dictType = list
      return list ? list : []
    },
  },
  watch: {
    value(v) {
      let show = v ? true : false,
        change = false
      this.dialogFormVisible !== show
        ? ((this.dialogFormVisible = show), (change = true))
        : null
      if (v && change) {
        this.title = v.method === 'add' ? '添加' : '修改'
        // this.$refs.form ? this.$refs.form.resetFields() : null
        if (typeof v === 'object') {
          for (let k in this.form) {
            typeof this.form[k] == 'string' || typeof this.form[k] == 'number'
              ? (this.form[k] = v[k] || v[k] === 0 ? v[k] : '')
              : (this.form[k] = v[k] || v[k] === 0 ? [v[k]] : [])
          }
          this.form.menuKind = this.form.menuKind.toString()
        } else {
          for (let k in this.form) {
            typeof this.form[k] == 'string' || typeof this.form[k] == 'number'
              ? (this.form[k] = '')
              : (this.form[k] = [])
          }
        }
        this.$nextTick(() => {
          // console.log(this.form)
          this.$refs.form ? this.$refs.form.clearValidate() : null
        })
        if (v.method === 'add' && v.parentId) {
          this.disabled = true
        } else {
          this.disabled = false
        }
      }
    },
    dialogFormVisible(v) {
      v
        ? null
        : this.$emit('input', !v && this.value.method == 'edit' ? null : v)
    },
    'form.menuKind'(v) {
      let ids = this.recursion({ children: this.menus_ })
      ids.indexOf(this.form.parentId) == -1 ? (this.form.parentId = '') : null
    },
  },
  methods: {
    judgeDisabled(item) {
      let value = this.value
      if (value && value.method === 'add' && value.parentKind !== undefined) {
        switch (Number(item.dictCode)) {
          case 0:
            return !(
              Number(item.dictCode) >= Number(value.parentKind) &&
              Number(item.dictCode) <= Number(value.parentKind) + 1
            )
          case 1:
            return !(
              Number(item.dictCode) >= Number(value.parentKind) &&
              Number(item.dictCode) <= Number(value.parentKind) + 1
            )
          case 2:
            return !(
              Number(item.dictCode) > Number(value.parentKind) &&
              Number(item.dictCode) <= Number(value.parentKind) + 1
            )
        }
      } else {
        return false
      }
    },
    toFilters(list) {
      return list.filter((item) => {
        // console.log(item.children)
        item.children && item.children.length > 0
          ? (item.children = this.toFilters([...item.children]))
          : null
        let childLength = item.children.filter((v) => !v.disabled)
        let judge = true
        if (this.form.menuKind || this.form.menuKind === 0) {
          if (this.form.menuKind == '0') {
            judge =
              item.menuKind != '1' && (!this.value || item.id !== this.value.id)
          } else if (this.form.menuKind == '1') {
            judge =
              (item.menuKind == '0' || item.menuKind == '1') &&
              (!this.value || item.id !== this.value.id)
          } else if (this.form.menuKind == '2') {
            item.disabled = item.menuKind == '0' ? true : false
            if (item.menuKind == '0') {
              childLength == 0 ? (judge = false) : null
            }
          }
        }
        return item.menuKind != '2' && judge
      })
    },
    returnTree(v) {
      // console.log(v)
      if (this.value.method == 'add') {
        if (v.length > 0) {
          this.$emit('input', {
            ...this.value,
            parentKind: v[0].menuKind,
          })
        } else {
          this.$emit('input', {
            method: this.value.method,
          })
        }
      }
    },
    submitForm() {
      if (this.ajaxIng) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          // console.log(this.form)
          let param = {
            ...this.form,
          }
          if (this.value.method === 'edit' && this.value.id) {
            param.id = this.value.id
          } else {
            param.menuStatus = 1
          }
          if (param.menuKind == 0) {
            delete param.menuAddr
            // delete param.menuCode
          } else if (param.menuKind == 1) {
          } else {
            delete param.menuAddr
            delete param.menuIcon
          }
          param.parentId ? null : (param.parentId = '0')
          this.ajaxIng = true
          let title = this.title
          this.API.menuManage[
            `${
              this.value.method === 'edit' && this.value.id ? 'update' : 'add'
            }Menu`
          ](param)
            .then((res) => {
              this.$alertFn.success(`${title}成功 ！`)
              this.ajaxIng = false
              this.dialogFormVisible = false
              this.$emit('change')
            })
            .catch((err) => {
              this.ajaxIng = false
              // this.$alertFn.error(`${title}失败 ！`)
            })
        } else {
          // console.log('error submit!!')
          // this.$alertFn.error(`${title}失败，请修改 ！`)
          return false
        }
      })
    },
  },
}
</script>
<style scoped>
.helpTooltip {
  position: absolute;
  right: -24px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  color: #909399;
}
</style>